# -*- coding:utf-8 -*-
from django.shortcuts import render, HttpResponseRedirect, HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import CreateView, UpdateView, DeleteView
from models import Post, SearchFrom
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import get_object_or_404
from taggit.models import Tag
from ckeditor_uploader.widgets import CKEditorUploadingWidget
from django import forms
from django.contrib.auth.decorators import login_required, permission_required
from django.utils.decorators import method_decorator
from django.db.models import Q
import re


# 展示列表页
@login_required
def post_list(request, tag_name=None):
	object_list = Post.objects.all()
	tag_lists = Post.objects.all()
	if tag_name:
		tag = get_object_or_404(Tag, name=tag_name)
		object_list = Post.objects.filter(tags__in=[tag])

	if request.method == 'POST':
		form = SearchFrom(request.POST)
		if form.is_valid():
			query = form.cleaned_data['search']
			return HttpResponseRedirect("/search/" + query)

	else:
		form = SearchFrom()
	paginator = Paginator(object_list, 10)  # 3 posts in each page
	page = request.GET.get('page')

	try:
		posts = paginator.page(page)
	except PageNotAnInteger:
		# If page is not an integer deliver the first page
		posts = paginator.page(1)
	except EmptyPage:
		# If page is out of range deliver last page of results
		posts = paginator.page(paginator.num_pages)
	return render(request, 'blog/post/list.html', {'posts': posts,
	                                               'form': form, 'tag': tag_name, 'tag_lists': tag_lists})


@login_required
def first_page(request):
	return HttpResponseRedirect("/")


class PostCreateView(CreateView):
	model = Post
	template_name = 'blog/post/create.html'
	# success_url = reverse_lazy('first_page')
	fields = ['title', 'body', 'tags', 'uploads']

	@method_decorator(permission_required("blog.add_post", raise_exception=True))
	def dispatch(self, request, *args, **kwargs):
		return super(PostCreateView, self).dispatch(request)

	def get_success_url(self):
		return reverse('post_detail', args=(self.object.id,))

	def get_form(self, form_class=None):
		form = super(PostCreateView, self).get_form(form_class)
		form.fields['uploads'].widget = CKEditorUploadingWidget()
		form.fields['uploads'].required = False
		form.fields['body'].widget = forms.Textarea(attrs={
			'style': 'height: 595px;background:	#90EE90',
			'id': 'markdown',
			'class': 'full-height',
			'placeholder': "Write Markdown"})
		form.fields['title'].widget = forms.TextInput(attrs={
			"style": "margin: 10px;width: 50%"

		})
		form.fields['tags'].widget.attrs = {
			"style": "margin: 10px"}
		return form


class PostDeleteView(DeleteView):
	model = Post
	template_name = 'blog/post/delete.html'
	success_url = reverse_lazy('first_page')

	@method_decorator(permission_required("blog.delete_post", raise_exception=True))
	def dispatch(self, request, *args, **kwargs):
		return super(PostDeleteView, self).dispatch(request)


class PostUpdateView(UpdateView):
	model = Post
	fields = ['title', 'body', 'tags', 'uploads']
	template_name = 'blog/post/create.html'

	@method_decorator(permission_required("blog.change_post", raise_exception=True))
	def dispatch(self, request, *args, **kwargs):
		return super(PostUpdateView, self).dispatch(request)

	def get_success_url(self):
		return reverse('post_detail', args=(self.object.id,))

	def get_form(self, form_class=None):
		form = super(PostUpdateView, self).get_form(form_class)
		form.fields['uploads'].widget = CKEditorUploadingWidget()
		form.fields['uploads'].required = False
		form.fields['body'].widget = forms.Textarea(attrs={
			'style': 'height: 595px;background:	#90EE90',
			'id': 'markdown',
			'class': 'full-height',
			'placeholder': "Write Markdown"})
		form.fields['title'].widget = forms.TextInput(attrs={
			"style": "margin: 10px;width: 50%"

		})
		form.fields['tags'].widget.attrs = {
			"style": "margin: 10px"}
		return form


@login_required
def detail(request, pk):
	post = Post.objects.filter(id=pk)[0]
	posts = Post.objects.all()
	if request.method == 'POST':
		form = SearchFrom(request.POST)
		if form.is_valid():
			query = form.cleaned_data['search']
			return HttpResponseRedirect("/search/" + query)

	else:
		form = SearchFrom()
	return render(request, 'blog/post/detail.html', {'post': post, 'form': form, 'posts': posts})


##haystak的whoosh我不喜欢，而且使用simple。backup算法有错无法修改并集、或集
def mysearch(request, query):
	tag_lists = Post.objects.all()
	get_str = re.split('\s*', query)  # 按空格分割字符，得到非空字符列表
	search_condition_list = []  # 一系列查询条件，使用AND连接起来
	for search_name in get_str:
		search_condition_list.append(Q(body__contains=search_name) | Q(title__contains=search_name))
	reduce(lambda x, y: Q(x & y), search_condition_list)
	search_list = Post.objects.filter(reduce(lambda x, y: Q(x & y), search_condition_list))

	if request.method == 'POST':
		form = SearchFrom(request.POST)
		if form.is_valid():
			query = form.cleaned_data['search']
			return HttpResponseRedirect("/search/" + query)
	else:
		form = SearchFrom()

	paginator = Paginator(search_list, 10)
	page = request.GET.get('page')
	try:
		posts = paginator.page(page)
	except PageNotAnInteger:
		# If page is not an integer, deliver first page.
		posts = paginator.page(1)
	except EmptyPage:
		# If page is out of range (e.g. 9999), deliver last page of results.
		posts = paginator.page(paginator.num_pages)
	return render(request, 'blog/post/search.html',
	              {"posts": posts, 'query': query, 'form': form, 'tag_lists': tag_lists})
